<?php
//设置时区
date_default_timezone_set('Asia/Shanghai');  // 推荐



require 'webapp/webapp_stdio.php';
require 'models/redis.php';
require 'models/base.php';
require 'models/task.php';

class webapp_router_admin extends webapp_echo_admin
{
    const MENUS = [
        ['首页', 'url' => '/admin.php?admin/home', 'icon' => 'home'],
        ['管理员', 'url' => '/admin.php?admin/admin', 'icon' => 'admin'],
        ['用户管理', 'url' => '/admin.php?admin/user', 'icon' => 'user'],
        ['分组管理', 'url' => '/admin.php?admin/group', 'icon' => 'group'],
        ['代理管理', 'url' => '/admin.php?admin/proxy', 'icon' => 'proxy'],
        ['评论任务', 'url' => '/admin.php?admin/task,action:comment', 'icon' => 'comment'],
        ['点赞任务', 'url' => '/admin.php?admin/task,action:like', 'icon' => 'heart'],
        ['收藏任务', 'url' => '/admin.php?admin/task,action:collect', 'icon' => 'star'],
        ['关注任务', 'url' => '/admin.php?admin/task,action:follow', 'icon' => 'focus'],
        ['曝光任务', 'url' => '/admin.php?admin/task,action:exposure', 'icon' => 'view']
    ];
    const ALL_STATUSES = [
        'active' => '激活',
        'normal' => '正常',
        'disabled' => '禁用',
        'expired' => '过期',
        'frozen' => '冻结',
        'like' => '点赞',
        'collect' => '收藏',
        'follow' => '关注',
        'comment' => '评论',
        'exposure' => '曝光',
        'pending' => '待处理',
        'running' => '运行中',
        'completed' => '已完成',
        'failed' => '失败',
        'closed' => '关闭',
        'notfound' => '未找到',
        'timeout' => '已超时',
        'success' => '成功',
        'unchecked' => '未审核',
        'passed' => '已审核',
        'abnormal' => '异常',
        'relogin' => '需重新登录',
        'disabled' => '不可用',
        'nocomment' => '禁言',
        'running' => '运行中',
        'completed' => '已完成',
        'pending' => '待处理',
        'paused' => '已暂停',

    ];
    private $menus = [];
    private $contentNode;
    private $user = [];


    function __construct(webapp $webapp, webapp|string $authenticate = NULL, string ...$allow)
    {
        parent::__construct($webapp, $authenticate, ...$allow);
        unset($this->xml->body->div->footer);
        // if(isset($this->xml->head->link[1])) $this->xml->head->link[1]['href'] = '/static/comm.css?v=' . time();
        $this->xml->head->append("link", ['rel' => 'stylesheet', 'href' => '/static/comm.css?v=' . time()]);
        $this->xml->head->append("link", ['rel' => 'stylesheet', 'href' => '/static/table.css?v=' . time()]);
        $this->xml->head->append("script", ['type' => 'text/javascript', 'src' => '/static/comm.js?v=' . time()]);
        $this->xml->head->title[0] = "开心的工作，快乐的生活";

        if ($this->auth) {
            $uinfo = explode(",", $this->auth[2]);
            foreach ($uinfo as $val) {
                $val = explode(":", $val);
                $this->user[$val[0]] = $val[1];
            }
            $this->user['name'] = $this->auth[0];

            $this->xml->body->div['class'] = $this->webapp->request_cookie("aside") == "hide"
                ? "container iconslide"
                : "container";

            $this->xml->body->div->header->append("h1", "推流引擎后台管理系统");
            $userDiv = $this->xml->body->div->header->append("div", ['class' => 'user']);
            $userDiv->append("span", ["欢迎您：" . $this->user['name'], 'class' => 'username']);
            $userDiv->append("button", ['退出登录', 'class' => 'logout', 'onclick' => 'location.href="/admin.php?admin/logout"']);

            $noticeNode = $this->main->append('div', ['class' => 'notice']);
            $noticeNode->append('span', ['class' => 'menu']);
            $noticeNode->append('span', ['class' => 'back', 'onclick' => 'history.go(-1)']);
            $noticeNode->append('span', ['class' => 'back front', 'onclick' => 'history.go(1)']);
            $noticeNode->append('p', [
                $this->raddomLyrics(),
                'class' => 'nowrap'
            ]);

            $ulNode = $this->aside->append('ul', ['class' => 'nav']);
            foreach ($this->menus as $menu) {
                $aNode = $ulNode->append('li')->append('a', ['href' => $menu['url']]);
                $aNode->append("span", [$menu[0]]);
                $aNode->append('img', ['src' => '/static/img/' . $menu['icon'] . '.svg']);
            }

            $this->contentNode = $this->main->append('div', ['class' => 'content']);
        } else {
            $this->xml->body['name'] = 'login';
        }
    }

    function isSuperSuper(): bool
    {
        if ($this->auth) {
            return $this->auth[0] === $this->webapp['admin_username'] && $this->auth[1] === $this->webapp['admin_password'];
        }
        return false;
    }
    static function form_sign_in(array|webapp|webapp_html $context, ?string $authurl = NULL): webapp_form
    {
        $form = new webapp_form($context, $authurl);
        $form->fieldset('用户名');
        $form->field('username', 'text', ['placeholder' => '请输入用户名', 'required' => NULL, 'autofocus' => NULL]);
        $form->fieldset('密码');
        $form->field('password', 'password', ['placeholder' => '请输入密码', 'required' => NULL]);
        $form->captcha('验证码')->input[1]['placeholder'] = '请输入验证码';
        $form->fieldset();
        $form->button('登 录', 'submit');
        $form->xml['spellcheck'] = 'false';
        $form->xml['class'] = 'webapp';
        $form->xml['name'] = 'loginform';
        return $form;
    }

    function authenticate(string $username, string $password, int $signtime, string $additional = NULL): array
    {
        $this->menus = self::MENUS;
        if ($username === $this->webapp['admin_username'] && $password === $this->webapp['admin_password']) {
            return [$username, $password,  "uid:0,group_ids:all"];
        }
        unset($this->menus[1], $this->menus[3], $this->menus[4]);

        $user = $this->webapp->mysql("select id,username,group_ids from admin where username = ?s and password = ?s AND `status` = 'active' AND deleted_at IS NULL limit 1", $username, md5(md5($password)))->array();
        return $user ? [$user['username'], $password, "uid:{$user['id']},group_ids:{$user['group_ids']}"] : [];
    }

    function get_logout()
    {
        $this->webapp->response_cookie('webapp', '', -1);
        $this->webapp->response_location('/admin.php?admin');
    }

    function warn(string $text)
    {
        $this->contentNode->append('h4', $text);
    }
    function okay(string $goto = NULL): int
    {
        $this->webapp->response_location($goto
            ?? $this->webapp->request_referer('?'));
        return 302;
    }
    function get_home($page = 1)
    {
        // $this->contentNode->append('h2', '欢迎使用推流引擎后台管理系统V1.0.0,当前页面为预留页面');

        $start = ($page - 1) * 10;
        $sql = "SELECT 
                DATE(excute_at) AS execution_date,
                COUNT(*) AS total_tasks,
                SUM(CASE WHEN execution_status = 'success' THEN 1 ELSE 0 END) AS success_tasks,
                SUM(CASE WHEN execution_status = 'failed' THEN 1 ELSE 0 END) AS failed_tasks,
                SUM(CASE WHEN execution_status = 'pending' THEN 1 ELSE 0 END) AS pending_tasks,
                SUM(CASE WHEN execution_status = 'running' THEN 1 ELSE 0 END) AS running_tasks,
                GROUP_CONCAT(DISTINCT ACTION) AS task_actions
            FROM 
                task_detail
            WHERE 
                excute_at IS NOT NULL
            GROUP BY 
                DATE(excute_at)
            ORDER BY 
                execution_date DESC
            LIMIT {$start},10";
        $data = ($this->webapp->mysql)($sql)->all();
        $table = $this->contentNode->table($data, function ($table, $admin) {
            $table->row();
            $table->cell($admin['execution_date'] ?? "");
            $table->cell($admin['total_tasks'] ?? 0);
            $table->cell($admin['success_tasks'] ?? 0);
            $table->cell($admin['failed_tasks'] ?? 0);
            $table->cell($admin['pending_tasks'] ?? 0);
            $table->cell($admin['running_tasks'] ?? 0);
            // $table->cell($admin['task_actions'] ?? 0);
        });
        $table->fieldset("执行日期", "总任务数", "成功任务数", "失败任务数", "等待任务数", "执行中任务数");
        $table->header('总记录数： ' . $table->count());
        $table->paging($this->webapp->at(['page' => '']));
    }



    function get_admin(int $page = 1)
    {
        $groups = $this->webapp->mysql->table('group')->column('name', 'id');
        $cond = ['WHERE 1 = 1 AND deleted_at IS NULL ORDER BY id DESC'];
        $table = $this->contentNode->table($this->webapp->mysql->admin(...$cond)->paging($page, 10), function ($table, $admin) use ($groups) {
            $table->row();

            $table->cell($admin['id']);
            $table->cell($admin['username']);
            $cellNode = $table->cell(['class' => 'spans']);
            $groupIds = explode(',', $admin['group_ids']);
            $groupIds = array_filter($groupIds, function ($v) {
                return !empty($v);
            });
            foreach ($groupIds as $group_id) {
                $cellNode->append("span", [$groups[$group_id]]);
            }
            if (empty($groupIds)) {
                $cellNode->append("span", '系统分组');
            }
            $table->cell([$admin['status'], 'class' => self::ALL_STATUSES[$admin['status']] ?? $admin['status']]);
            $table->cell($admin['last_login_at']);
            $cellNode = $table->cell(['class' => 'actions']);
            $cellNode->append('a', [
                '❌',
                'href' => "?admin/admin-delete,id:{$admin['id']}",
                'onclick' => 'return confirm(`确定要删除管理员： ${this.dataset.id}`)',
                'data-id' => $admin['id']
            ]);

            $cellNode->append('a', [
                '✏️',
                'href' => "?admin/admin-update,id:{$admin['id']}",
            ]);
        });
        $table->fieldset("ID", '用户名', '拥有分组', '状态', '最后登录时间', '操作');
        $table->header('总记录数： ' . $table->count());
        $table->bar->append('button', ['添加管理员', 'class' => 'tbbtn', 'onclick' => 'location.href="?admin/admin-create"']);
        $table->paging($this->webapp->at(['page' => '']));
    }

    function get_admin_delete(string $id)
    {
        if ($this->isSuperSuper()) {
            $this->webapp->mysql->admin('WHERE id=?s ', $id)->update(['deleted_at' => date('Y-m-d H:i:s')]);
        }
        $this->okay('?admin/admin');
    }
    function post_admin_create()
    {
        $this->form_admin($this->webapp)->fetch($admin, $errors);
        $admin['password'] = md5(md5($admin['password']));
        $admin['group_ids'] = implode(',', $admin['group_ids'] ?? []);
        if ($this->isSuperSuper() && empty($errors) && $this->webapp->mysql->admin->insert($admin)) {
            return $this->okay('?admin/admin');
        }
        $this->warn('管理员创建失败！');
    }
    function get_admin_create()
    {
        $this->form_admin($this->contentNode)->echo(['status' => 'active']);
    }
    function get_admin_update(string $id)
    {
        if ($this->webapp->mysql->admin("WHERE id = ?s", $id)->fetch($item)) {
            $item['group_ids'] = $item['group_ids'] ?   explode(',', $item['group_ids']) : [];
            $this->form_admin($this->contentNode)->echo($item);
            return;
        }
        $this->warn('数据不存在');
    }
    function post_admin_update(int $id)
    {
        if ($id > 0) {
            $this->form_admin($this->webapp)->fetch($admin, $errors);
            $admin['group_ids'] = implode(',', $admin['group_ids'] ?? []);
            if (empty($errors) && $this->webapp->mysql->admin("WHERE id = ?s", $id)->update($admin) === 1) {
                return $this->okay('?admin/admin');
            }
            $this->warn('管理员更新失败！');
            return;
        }
    }
    function get_proxy(int $page = 1)
    {
        $cond = ['WHERE  deleted_at IS NULL ORDER BY id DESC'];
        $proxyTypes = [0 => '异常', 1 => 'socks5', 2 => 'http'];
        $table = $this->contentNode->table($this->webapp->mysql->table('proxy')(...$cond)->paging($page, 20), function ($table, $admin) use ($proxyTypes) {
            $table->row();

            $table->cell($admin['id']);
            $table->cell($admin['city']);
            $table->cell(sprintf("%s://%s:%s", $proxyTypes[$admin['type'] ?? 0],  $admin['ip'], $admin['port']));
            $table->cell($admin['user']);
            $table->cell($admin['password']);
            $table->cell($admin['expire_at']);
            $table->cell(self::ALL_STATUSES[$admin['status']] ?? $admin['status']);
            $cellNode = $table->cell(['class' => 'actions']);
            $cellNode->append('a', [
                '❌',
                'href' => "?admin/proxy-delete,id:{$admin['id']}",
                'onclick' => 'return confirm(`确定要删除： ${this.dataset.id}`)',
                'data-id' => $admin['id']
            ]);

            // $cellNode->append('a', [
            //     '✏️',
            //     'href' => "?admin/proxy-update,id:{$admin['id']}",
            // ]);
        });
        $table->fieldset("ID", '城市', '地址', '用户', '密码', '过期时间', '状态', '操作');
        $table->header('总记录数： ' . $table->count());
        // $table->bar->append('button', ['添加代理', 'class' => 'tbbtn', 'onclick' => 'location.href="?admin/proxy-create"']);
        $table->bar->append('button', ['批量添加', 'class' => 'tbbtn', 'onclick' => 'location.href="?admin/proxys-create"']);

        $table->paging($this->webapp->at(['page' => '']));
    }
    function get_proxy_delete(string $id)
    {
        if ($this->isSuperSuper()) {
            $this->webapp->mysql->table('proxy')('WHERE id=?s ', $id)->update(['deleted_at' => date('Y-m-d H:i:s')]);
        }
        $this->okay('?admin/proxy');
    }
    function post_proxy_create()
    {
        // $this->form_proxy($this->webapp)->fetch($item, $errors);
        // if (empty($errors)) {
        //     $item += [
        //         'platform' => 2,
        //         'create_at' => $time = date("Y-m-d H:i:s"),
        //         'update_at' => $time,
        //     ];
        // }
        // if (empty($errors) && $this->webapp->mysql->table('proxy')->insert($item)) {
        //     return $this->okay('?admin/proxy');
        // }
        // $this->warn('代理创建失败！');
    }
    function get_proxy_create()
    {
        $this->form_proxy($this->contentNode)->echo([
            'status' => 'active',
            'expire_at' => date('Y-m-d', $this->webapp->time + 30 * 86400),
            'password' => 'admin123465'
        ]);
    }

    function get_proxys_create()
    {
        $this->form_proxys($this->contentNode)->echo([
            'type' => 1
        ]);
    }

    function get_proxy_update(string $id)
    {
        if ($this->webapp->mysql->table('proxy')("WHERE id = ?s", $id)->fetch($item)) {
            $this->form_proxy($this->contentNode)->echo($item);
            return;
        }
        $this->warn('数据不存在');
    }
    function post_proxy_update(int $id)
    {
        // if ($id > 0) {
        //     $this->form_proxy($this->webapp)->fetch($item, $errors);
        //     if (empty($errors) && $this->webapp->mysql->table('proxy')("WHERE id = ?s", $id)->update($item) === 1) {
        //         return $this->okay('?admin/proxy');
        //     }
        //     $this->warn('数据更新失败！');
        //     return;
        // }
    }

    function post_proxys_create()
    {
        $this->form_proxys($this->webapp)->fetch($item, $errors);
        $type = intval($item['type'] ?? 0);
        if ($type !== 1 && $type !== 2) {
            return $this->warn('代理类型错误！');
        }

        $data = $item['data'] ?? "";
        if (empty($errors) && $data) {
            $data = array_filter(explode("\n", $data), function ($item) {
                return !empty(trim($item));
            });

            // 183.131.35.88/19106/nimdaa/admin123465/大连/25-09-25/25-10-25
            // 183.131.35.88/19107/nimdaa/admin123465/成都/25-09-25/25-10-25
            foreach ($data as $item) {
                $item = explode("/", trim($item));
                if (count($item) ==  7) {
                    $exists = $this->webapp->mysql->proxy("WHERE ip=?s AND port = ?s AND user = ?s AND password = ?s", $item[0], $item[1], $item[2], $item[3])->array();
                    if ($exists) {
                        $this->webapp->mysql->proxy("WHERE id = ?s", $exists['id'])->update([
                            'type' => $type,
                            'platform' => 2,
                            'city' => $item[4],
                            'status' => 'active',
                            'create_at' => date("Y-m-d"),
                            'update_at' => '20' . $item[5],
                            'expire_at' => '20' . $item[6],
                            'deleted_at' => null
                        ]);
                    } else {
                        $this->webapp->mysql->proxy->insert([
                            'type' => $type,
                            'platform' => 2,
                            'ip' => $item[0],
                            'port' => $item[1],
                            'user' => $item[2],
                            'password' => $item[3],
                            'city' => $item[4],
                            'status' => 'active',
                            'create_at' => date("Y-m-d"),
                            'update_at' => '20' . $item[5],
                            'expire_at' => '20' . $item[6],
                        ]);
                    }
                }
            }

            return $this->okay('?admin/proxy');
        }
        $this->warn('批量操作代理创建失败,请检查格式！');
    }
    function form_proxys($ctx): webapp_form
    {
        $form = new webapp_form($ctx);

        $form->fieldset('类型');
        $form->field("type", "select", [
            'options' => ['1' => 'socks5', '2' => 'http'],
        ]);

        $form->fieldset('导入数据，数据格式：ip/端口/账号/密码/地区/购买/到期 ');
        $form->field('data', 'textarea', [
            'rows' => "30",
            'cols' => "40"
        ]);

        $form->fieldset();
        $form->button(' 提 交 ', 'submit', ['class' => 'tbbtn']);
        return $form;
    }


    function form_proxy($ctx): webapp_form
    {
        // $form = new webapp_form($ctx);

        // $form->fieldset('类型');
        // $form->field('type', 'select', [
        //     'options' => [
        //         '1' => 'socks5',
        //         '2' => 'http',
        //     ],
        // ]);

        // $form->fieldset('IP');
        // $form->field('ip', 'text');

        // $form->fieldset('端口');
        // $form->field('port', 'number');

        // $form->fieldset('用户名');
        // $form->field('user', 'text');

        // $form->fieldset('密码');
        // $form->field('password', 'text');

        // $form->fieldset('过期时间');
        // $form->field('expire_at', 'date', ['required' => null]);

        // $form->fieldset("状态");
        // $form->field("status", "radio", [
        //     'options' => ['active' => 'active', 'disable' => 'disable'],
        // ]);

        // $form->fieldset();
        // $form->button(' 提 交 ', 'submit', ['class' => 'tbbtn']);
        // return $form;
    }


    function form_admin($ctx): webapp_form
    {
        $form = new webapp_form($ctx);

        $form->fieldset('用户名');
        $form->field('username', 'text', ['required' => NULL]);

        $form->fieldset('密码');
        $form->field('password', 'text', ['required' => NULL]);


        $form->fieldset('选择分组');
        $form->field('group_ids', 'checkbox', [
            'options' => $this->webapp->mysql->table('group')('WHERE deleted_at is null')->column('name', 'id'),
        ]);

        $form->fieldset("状态");
        $form->field("status", "radio", [
            'options' => ['active' => 'active', 'disabled' => 'disabled'],
        ]);

        $form->fieldset();
        $form->button(' 提 交 ', 'submit', ['class' => 'tbbtn']);
        return $form;
    }



    function get_group(int $page = 1)
    {
        $cond = ['WHERE  deleted_at IS NULL ORDER BY id DESC'];
        $table = $this->contentNode->table($this->webapp->mysql->table('group')(...$cond)->paging($page, 10), function ($table, $admin) {
            $table->row();

            $table->cell($admin['id']);
            $table->cell($admin['name']);
            $table->cell($admin['description']);
            $cellNode = $table->cell(['class' => 'actions']);
            $cellNode->append('a', [
                '❌',
                'href' => "?admin/group-delete,id:{$admin['id']}",
                'onclick' => 'return confirm(`确定要删除： ${this.dataset.id}`)',
                'data-id' => $admin['id']
            ]);

            $cellNode->append('a', [
                '✏️',
                'href' => "?admin/group-update,id:{$admin['id']}",
            ]);
        });
        $table->fieldset("ID", '名称', '描述', '操作');
        $table->header('总记录数： ' . $table->count());
        $table->bar->append('button', ['添加分组', 'class' => 'tbbtn', 'onclick' => 'location.href="?admin/group-create"']);
        $table->paging($this->webapp->at(['page' => '']));
    }

    function get_group_delete(string $id)
    {
        if ($this->isSuperSuper()) {
            $this->webapp->mysql->table('group')('WHERE id=?s ', $id)->update(['deleted_at' => date('Y-m-d H:i:s')]);
        }
        $this->okay('?admin/group');
    }
    function post_group_create()
    {
        $this->from_group($this->webapp)->fetch($item, $errors);
        if (empty($errors) && $this->webapp->mysql->table('group')->insert($item)) {
            return $this->okay('?admin/group');
        }
        $this->warn('管理员创建失败！');
    }
    function get_group_create()
    {
        $this->from_group($this->contentNode);
    }
    function get_group_update(string $id)
    {
        if ($this->webapp->mysql->table('group')("WHERE id = ?s", $id)->fetch($item)) {
            $this->from_group($this->contentNode)->echo($item);
            return;
        }
        $this->warn('数据不存在');
    }
    function post_group_update(int $id)
    {
        if ($id > 0) {
            $this->from_group($this->webapp)->fetch($item, $errors);
            if (empty($errors) && $this->webapp->mysql->table('group')("WHERE id = ?s", $id)->update($item) === 1) {
                return $this->okay('?admin/group');
            }
            $this->warn('数据更新失败！');
            return;
        }
    }

    function from_group($ctx): webapp_form
    {
        $form = new webapp_form($ctx);

        $form->fieldset('分组名称');
        $form->field('name', 'text', ['required' => NULL]);

        $form->fieldset('描述');
        $form->field('description', 'text');

        $form->fieldset();
        $form->button(' 提 交 ', 'submit', ['class' => 'tbbtn']);
        return $form;
    }

    function form_user_search($ctx): webapp_form
    {
        $form = new webapp_form($ctx);
        $form->xml['class'] = 'webapp';
        $form->xml['method'] = 'get';
        $form->xml['name'] = 'search';


        $form->fieldset('ID');
        $form->field('id', 'number', [
            'onkeydown' => 'if (event.keyCode == 13) {at({id:this.value||null});return false;}',
        ]);
        $form->fieldset('UID');
        $form->field('uid', 'number', [
            'onkeydown' => 'if (event.keyCode == 13) {at({uid:this.value||null});return false;}',
        ]);

        $form->fieldset('名称');
        $form->field('name', 'text', [
            'onkeydown' => 'if (event.keyCode == 13) {at({name:this.value||null});return false;}',
        ]);

        $form->fieldset('状态');
        $form->field('status', 'select', [
            'options' => ["" => '全部'] + [
                'normal' => self::ALL_STATUSES['normal'] ?? 'normal',
                'abnormal' => self::ALL_STATUSES['abnormal'] ?? 'abnormal',
                'relogin' => self::ALL_STATUSES['relogin'] ?? 'relogin',
                'disabled' => self::ALL_STATUSES['disabled'] ?? 'disabled',
                'nocomment' => self::ALL_STATUSES['nocomment'] ?? 'nocomment',
            ],
            'onchange' => 'at({status:this.value||null})'
        ]);
        return $form;
    }
    function get_user(int $page = 1)
    {
        $groups = $this->webapp->mysql->table('group')("ORDER BY id DESC")->column('name', 'id');
        // $cond = ['WHERE  deleted_at IS NULL '];
        // if (!$this->isSuperSuper()) {
        //     $cond[0] .= "AND group_id IN (?s) ";
        //     $cond[] = $this->user['group_ids'];
        // }
        // $cond[0] .= "ORDER BY id DESC";


        $cond = $this->webapp->cond();
        $cond->query('action', 'deleted_at is null');
        if (!$this->isSuperSuper()) {
            $cond->query('group_id', 'group_id in (?s)', fn() => $this->user['group_ids']);
        }

        $id = $cond->query("id", '`id` = ?i', fn($v) => $v);
        $uid = $cond->query("uid", '`uid` = ?i', fn($v) => $v);
        $name = $cond->query("name", '`name` like ?s', fn($v) => "%$v%");
        $status = $cond->query("status", '`status` = ?s', fn($v) => $v);

        $cond->merge('ORDER BY id DESC');

        $this->form_user_search($this->contentNode)->echo([
            'id' => $id,
            'uid' => $uid,
            'name' => $name,
            'status' => $status,
        ]);


        $table = $this->contentNode->table($cond($this->webapp->mysql->user)->paging($page, 10), function ($table, $admin) use ($groups) {
            $table->row();
            $table->cell()->append('input', ['type' => 'checkbox', 'name' => 'ids[]', 'value' => $admin['id']]);
            $table->cell($admin['id']);
            $table->cell($admin['type']);
            $table->cell($admin['uid']);
            $table->cell($admin['name']);
            $table->cell()->append("img", ['src' => $admin['header'], 'class' => 'bicon']);
            $table->cell([self::ALL_STATUSES[$admin['status']] ?? $admin['status'], 'class' => $admin['status']]);
            $table->cell(['class' => 'spans'])->append('span', $admin['group_id'] ? $groups[$admin['group_id']]  : '系统默认');
            $table->cell($admin['city']);
            $table->cell($admin['create_at']);

            $cellNode = $table->cell(['class' => 'actions']);
            $cellNode->append('a', [
                '❌',
                'href' => "?admin/user-delete,id:{$admin['id']}",
                'onclick' => 'return confirm(`确定要删除： ${this.dataset.id}`)',
                'data-id' => $admin['id']
            ]);
        });
        $table->fieldset("全选", "ID", '类型', 'UID', '名称', '头像', '状态', '分组', '城市', '创建时间', '操作');
        $table->tbody->tr->td['class'] = 'selectall';
        $table->header('总记录数： ' . $table->count());
        $barNode = $table->bar;
        $barNode['style'] = "display:none;";
        $barNode->parent()['style'] = "display:none";

        $spanNode = $barNode->append("div", ['class' => 'selectcount']);
        $spanNode->append('font', ['当前选中']);
        $spanNode->append('font', [0, 'class' => 'count']);
        $spanNode->append('font', ['项']);

        $barNode->append('button', ['批量删除', 'class' => 'tbbtn', 'id' => 'deleteAll', 'data-action' => '?admin/user-delete']);
        $formNode = $barNode->append('form', ['method' => 'post', 'action' => '?admin/user-delete', 'id' => 'batchForm']);
        $formNode->append('input', ['type' => 'hidden', 'name' => 'ids', 'value' => '']);
        $groupNode = $formNode->append('select', ['name' => 'group_id', 'id' => 'changeGroup', 'data-action' => '?admin/user-change-group']);
        $groupNode->append('option', ['选择转移的目标分组', 'value' => '']);
        foreach ($groups as $id => $name) {
            $groupNode->append('option', ['value' => $id, $name]);
        }
        $table->paging($this->webapp->at(['page' => '']));
    }

    function delete_redis_user(string $ids = '')
    {
        if ($ids) {
            $ids = explode(',', $ids);
            foreach ($ids as $id) {
                intval($id) > 0 && $this->webapp->rds->del("user:{$id}");
            }
        }
    }
    function get_user_delete(string $id)
    {
        if ($this->isSuperSuper()) {
            $this->webapp->mysql->table('user')('WHERE id=?s ', $id)->update(['deleted_at' => date('Y-m-d H:i:s')]);
            $this->delete_redis_user($id);
        }
        $this->okay('?admin/user');
    }

    function post_user_delete()
    {
        $ids = trim($this->webapp->request_content()['ids'] ?? "", ',');
        if ($this->isSuperSuper() && $ids) {
            $this->webapp->mysql->table('user')('WHERE id IN ( ' . $ids . ')')->update(['deleted_at' => date('Y-m-d H:i:s')]);
            $this->delete_redis_user($ids);
        }
        $this->okay('?admin/user');
    }


    function post_user_change_group()
    {
        $ids = trim($this->webapp->request_content()['ids'] ?? "", ',');
        $groupId = intval($this->webapp->request_content()['group_id'] ?? "");
        if ($this->isSuperSuper() && $ids && $groupId) {
            $this->webapp->mysql->table('user')('WHERE id IN (' . $ids . ')')->update(['group_id' => $groupId]);
            $this->delete_redis_user($ids);
        }
        $this->okay('?admin/user');
    }

    function get_task_create(string $action, string $link = "", int $times = 10)
    {
        $this->form_task($this->contentNode)->echo([
            'times' => 10,
            'interval_time' => 0,
            'action' => $action,
            'link' => $link ? $this->webapp->url64_decode($link) : '',
            'times' => $times,
        ]);
    }
    function get_task_edit(int $id)
    {
        $taskDt = $this->webapp->mysql->table('task')('WHERE id=?s ', $id)->array();
        $this->form_task_link($this->contentNode)->echo([
            'link' => $taskDt['link'],
        ]);
    }

    function post_task_edit(int $id)
    {
        $this->form_task_link($this->webapp)->fetch($item, $errors);
        if (empty($errors)) {
            $this->webapp->mysql->table('task')('WHERE id=?s ', $id)->update(['link' => $item['link']]);
            $this->webapp->mysql->table('task_detail')('WHERE task_id=?s ', $id)->update(['link' => $item['link']]);
            $this->okay('?admin/task');
            return;
        }
        $this->warn('数据添加失败！');
        return;
    }

    function form_task_link($ctx): webapp_form
    {
        $form = new webapp_form($ctx);
        $form->xml['class'] = 'webapp';

        $form->fieldset('链接');
        $form->field('link', 'url', ['required' => '']);

        $form->fieldset();
        $form->button(' 修 改 ', 'submit', ['class' => 'tbbtn']);
        return $form;
    }


    function post_task_create()
    {
        $this->form_task($this->webapp)->fetch($item, $errors);
        if (empty($errors)) {
            $task = $item + [
                'type' => 'redbook',
                'hash' => md5($item['link']),
                'create_at' => date('Y-m-d H:i:s'),
                'admin_id' => $this->user['uid'],
                'status' => 'pending',
            ];
            if ($this->webapp->mysql->table('task')->insert($task)) {
                $insertId = $this->webapp->mysql->insert_id;
                $this->webapp->task->afterAdd($insertId);

                return $this->okay('?admin/task,action:' . $item['action']);
            }
        }

        $this->warn('数据添加失败！');
        return;
    }

    function form_task($ctx): webapp_form
    {
        $form = new webapp_form($ctx);
        $form->xml['class'] = 'webapp';

        $form->fieldset('动作类型');
        $form->field('action', 'select', ['required' => NULL, 'id' => 'actionSelect',  'options' => [
            'like' => self::ALL_STATUSES['like'] ?? 'like',
            'collect' => self::ALL_STATUSES['collect'] ?? 'collect',
            'follow' => self::ALL_STATUSES['follow'] ?? 'follow',
            'comment' => self::ALL_STATUSES['comment'] ?? 'comment',
            'exposure' => self::ALL_STATUSES['exposure'] ?? 'exposure',
        ]]);

        $form->fieldset('链接');
        $form->field('link', 'url', ['required' => '']);

        $form->fieldset('执行次数');
        $form->field('times', 'number', ['required' => NULL]);

        $form->fieldset('间隔时长（单位：秒。可以设置为 0 系统会尽快执行）');
        $form->field('interval_time', 'number', ['required' => NULL]);

        $form->fieldset('评论内容(一行一评论，支持换行)');
        $form->field('content', 'textarea', ['name' => "otoiawase", 'rows' => "11", 'cols' => "40"]);


        $groups = $this->isSuperSuper()
            ? $this->webapp->mysql->table('group')("ORDER BY id DESC")->column('name', 'id')
            : $this->webapp->mysql->table('group')("WHERE id = (?s) ORDER BY id DESC", $this->user['group_ids'])->column('name', 'id');

        $form->fieldset('选择分组');
        $form->field('group_id', 'select', [
            'options' => [0 => '建议不选（保持此项）'] + $groups
        ]);


        $form->fieldset();
        $form->button(' 添 加 ', 'submit', ['class' => 'tbbtn']);
        return $form;
    }

    function form_task_detail_search($ctx, $admins): webapp_form
    {
        $form = new webapp_form($ctx);
        $form->xml['class'] = 'webapp';
        $form->xml['method'] = 'get';
        $form->xml['name'] = 'search';

        $form->fieldset('链接HASH');
        $form->field('hash', 'text', [
            'onkeydown' => 'if (event.keyCode == 13) {at({hash:this.value||null});return false;}',
        ]);

        $form->fieldset('任务ID');
        $form->field('task_id', 'number', [
            'onkeydown' => 'if (event.keyCode == 13) {at({task_id:this.value||null});return false;}',
        ]);

        $form->fieldset('动作类型');
        $form->field('action', 'select', [
            'options' => ["" => '全部'] + [
                'like' => self::ALL_STATUSES['like'] ?? 'like',
                'collect' => self::ALL_STATUSES['collect'] ?? 'collect',
                'follow' => self::ALL_STATUSES['follow'] ?? 'follow',
                'comment' => self::ALL_STATUSES['comment'] ?? 'comment',
                'exposure' => self::ALL_STATUSES['exposure'] ?? 'exposure',
            ],
            'onchange' => 'at({action:this.value||null})'
        ]);

        $form->fieldset('状态');
        $form->field('execution_status', 'select', [
            'options' => ["" => '全部'] + [
                'pending' => self::ALL_STATUSES['pending'] ?? 'pending',
                'running' => self::ALL_STATUSES['running'] ?? 'running',
                'success' => self::ALL_STATUSES['success'] ?? 'success',
                'failed' => self::ALL_STATUSES['failed'] ?? 'failed',
            ],
            'onchange' => 'at({execution_status:this.value||null})'
        ]);
        return $form;
    }
    function get_task_detail(int $page = 1)
    {
        $groups = $this->webapp->mysql->table('group')("ORDER BY id DESC")->column('name', 'id');
        $admins = $this->webapp->mysql->table('admin')->column("username", 'id');

        $cond = $this->webapp->cond('`deleted_at` is null');
        $task_id = $cond->query("task_id", '`task_id` = ?i', fn($v) => intval($v));
        $action  = $cond->query("action", '`action` = ?s', fn($v) => $v);
        // $id = $cond->query("id", '`id` = ?i', fn($v) => $v);
        $execution_status = $cond->query("execution_status", '`execution_status` = ?s', fn($v) => $v);

        // $link = $cond->query("link", '`hash` = md5(?s)', fn($v) => $this->webapp->url64_decode($v));

        // $cond->query("deleted_at", '`deleted_at` is null');
        $hash = $cond->query("hash", '`hash` = ?s', fn($v) => trim($v));

        $cond->merge('ORDER BY excute_at ASC');

        $this->form_task_detail_search($this->contentNode, $admins)->echo([
            'task_id' => $task_id,
            'action' => $action,
            'hash' => $hash,
            'execution_status' => $execution_status,
        ]);


        $table = $this->contentNode->table($cond($this->webapp->mysql->task_detail)->paging($page, 12), function ($table, $admin) use ($groups, $admins) {
            $table->row();
            $table->cell($admin['task_id']);
            $table->cell($admin['id']);
            $table->cell([self::ALL_STATUSES[$admin['execution_status']] ?? $admin['execution_status'], 'class' => $admin['execution_status']]);


            $table->cell($admin['action'] == 'comment' ? $admin['content'] : self::ALL_STATUSES[$admin['action']] ?? $admin['action']);
            $table->cell($admin['excute_at']);
            if (intval($admin['excute_uid']) > 0) {
                $table->cell()->append('a', [$admin['excute_uid'], 'href' => "?admin/user,id:{$admin['excute_uid']}", 'target' => '_blank', 'class' => 'nowrap noscale']);
            } else {
                $table->cell('待分配');
            }

            $table->cell(empty($admin['push_at']) ? '未推送' : $admin['push_at']);
            $table->cell()->append("a", [$admin['hash'], 'href' => $admin['link'], 'target' => '_blank', 'class' => 'nowrap']);
        });
        $table->fieldset('任务ID', "ID", "执行状态", '内容', '预计执行时间', '执行用户',  '推送时间',  '链接HASH');
        $table->tbody->tr->td['class'] = 'selectall';
        $table->header('总记录数： ' . $table->count());


        $table->paging($this->webapp->at(['page' => '']));
    }


    function form_task_search($ctx, $admins, $action): webapp_form
    {
        $form = new webapp_form($ctx);
        $form->xml['class'] = 'webapp';
        $form->xml['method'] = 'get';
        $form->xml['name'] = 'search';

        if ($this->isSuperSuper()) {
            $form->fieldset('管理员ID');
            $form->field('admin_id', 'select', [
                'options' => ["" => '全部'] + $admins,
                'onchange' => 'at({admin_id:this.value||null})'
            ]);
        }

        $form->fieldset('ID');
        $form->field('id', 'number', [
            // 'onchange' =>'at({id:this.value||null})'
            'onkeydown' => 'if (event.keyCode == 13) {at({id:this.value||null});return false;}',
        ]);

        $form->fieldset('链接');
        $form->field('link', 'url', [
            'onkeydown' => 'if (event.keyCode == 13) {at({link:url64_encode(this.value)||null});return false;}',
        ]);

        $groups = $this->isSuperSuper()
            ? $this->webapp->mysql->table('group')("ORDER BY id DESC")->column('name', 'id')
            : $this->webapp->mysql->table('group')("WHERE id = (?s) ORDER BY id DESC", $this->user['group_ids'])->column('name', 'id');

        $form->fieldset('选择分组');
        $form->field('group_id', 'select', [
            'options' => ["" => '全部'] + $groups,
            'onchange' => 'at({group_id:this.value||null})'
        ]);

        // $form->fieldset('状态');
        // $form->field('status', 'select', [
        //     'options' => ["" => '全部'] + [
        //         'pending' => 'pending',
        //         'running' => 'running',
        //         'completed' => 'completed',
        //         'notfound' => 'notfound',
        //         'timeout' => 'timeout',
        //     ],
        //     'onchange' => 'at({status:this.value||null})'
        // ]);

        $form->xml->append('button', [
            '添加任务',
            'class' => 'tbbtn',
            'onclick' => "location.href = '?admin/task-create,action:{$action}';return false;",
            'style' => 'align-self: flex-end;'
        ]);
        return $form;
    }

    function get_task(string $action = '', int $page = 1)
    {
        $groups = $this->webapp->mysql->table('group')("ORDER BY id DESC")->column('name', 'id');
        $admins = $this->webapp->mysql->table('admin')->column("username", 'id');

        $cond = $this->webapp->cond('`deleted_at` is null');
        if ($this->isSuperSuper()) {
            $adminId = $cond->query('admin_id', 'admin_id = ?i', fn($v) => $v);
        } else {
            $cond->query('admin_id', 'admin_id = ?s', fn() => $this->user['uid']);
        }
        $cond->query("action", '`action` = ?s', fn() => $action);
        $id = $cond->query("id", '`id` = ?i', fn($v) => $v);
        $groudId = $cond->query("group_id", '`group_id` = ?i', fn($v) => $v);
        $status = $cond->query("status", '`status` = ?i', fn($v) => $v);

        $link = $cond->query("link", '`hash` = md5(?s)', fn($v) => $this->webapp->url64_decode($v));

        

        $cond->merge("ORDER BY id DESC");

        $this->form_task_search($this->contentNode, $admins, $action)->echo([
            'id' => $id,
            'group_id' => $groudId,
            'status' => $status,
            'link' => $link ? $this->webapp->url64_decode($link) : "",
            'admin_id' => $adminId
        ]);

        $actionIcons = [
            'comment' => 'comment',
            'like' => 'heart',
            'collect' => 'star',
            'follow' => 'focus',
            'exposure' => 'view'
        ];


        $datas = $cond($this->webapp->mysql->task)->paging($page,100)->all();

        $condddd = ["SELECT task_id,execution_status,COUNT(*) 'count' FROM task_detail  GROUP BY task_id,execution_status", implode(',', array_column($datas, 'id'))];
        $taskStatics = [];
        foreach (($this->webapp->mysql)(...$condddd) as $static) {
            $taskStatics[$static['task_id']][$static['execution_status']] = $static['count'];
        }

        $table = $this->contentNode->table($cond($this->webapp->mysql->task)->paging($page,100), function ($table, $admin) use ($groups, $admins, $actionIcons, $taskStatics) {

            $excuteTimes = intval($admin['times'] ?? 0);
            if ($admin['action'] == 'comment') {
                $excuteTimes = count(array_filter(explode("\n", trim($admin['content'] ?? ''))));
            }

            $table->row();
            $table->cell()->append('input', ['type' => 'checkbox', 'name' => 'ids[]', 'value' => $admin['id']]);
            $table->cell($admin['id']);
            $table->cell($admins[$admin['admin_id']] ?? "超管");
            $table->cell()->append("img", ['src' => '/static/img/' . $actionIcons[$admin['action']] . '.svg', 'class' => 'icon']);
            $table->cell([self::ALL_STATUSES[$admin['status']] ?? $admin['status'], 'class' => $admin['status']]);
            $cellNode = $table->cell(['class' => 'taskexec']);
            foreach ($taskStatics[$admin['id']] ?? [] as $status => $count) {
                $cellNode->append("a", [$count, 'href' => "?admin/task-detail,task_id:{$admin['id']},execution_status:{$status}", 'class' => $status, 'target' => '_blank']);
            }
            $table->cell()->append("a", [$excuteTimes, 'href' => "?admin/task-detail,task_id:{$admin['id']}", 'class' => 'nowrap ']);

            $table->cell(intval($admin['interval_time']) == 0 ? '自动分配' : $admin['interval_time']);
            $table->cell(['class' => 'spans'])->append('span', $admin['group_id'] ? $groups[$admin['group_id']]  : '系统默认');

            // $table->cell($admin['city']);
            $table->cell($admin['create_at']);
            $table->cell()->append("a", [$admin['hash'], 'href' => $admin['link'], 'target' => '_blank', 'class' => 'nowrap noscale']);
            $cellNode = $table->cell(['class' => 'actions']);

            if ($admin['status'] == 'running') {
                $cellNode->append('a', [
                    '⏸',
                    'href' => "?admin/task-paused,id:{$admin['id']}",
                    'style' => "margin-right:1rem;font-size:1.5rem;color:red;"
                ]);
            }
            if ($admin['status'] == 'paused') {
                $cellNode->append('a', [
                    '▶',
                    'href' => "?admin/task-start,id:{$admin['id']},hash:{$admin['hash']}",
                    'style' => "margin-right:1rem;font-size:1.5rem;color:green;"
                ]);
            }
            $cellNode->append('a', [
                '❌',
                'href' => "?admin/task-delete,id:{$admin['id']},action:{$admin['action']}",
                'onclick' => 'return confirm(`确定要删除： ${this.dataset.id}`)',
                'data-id' => $admin['id']
            ]);
            $cellNode->append('a', [
                ' 📄 ',
                'href' => "/admin.php?admin/task-create,action:{$admin['action']},times:{$admin['times']},link:" . $this->webapp->url64_encode($admin['link']),
                'title' => '复制任务新建',
                'style' => "margin:0 1rem"
            ]);
            $cellNode->append('a', [
                ' ✏️ ',
                'href' => "/admin.php?admin/task-edit,id:{$admin['id']}",
                'title' => '修改链接',
                'style' => "margin:0 1rem"
            ]);
            $cellNode->append('a', [
                '🛠',
                'href' => "?admin/task-fuck,hash:{$admin['hash']}",
                'target' => "_blank",
                'title' => '重新调整子任务执行时间'
            ]);
        });
        $table->fieldset("全选", "ID", '管理员', '操作类型', '状态',  '执行统计', '执行次数', '间隔时间', '分组',  '创建时间',  '链接HASH', '操作');
        $table->tbody->tr->td['class'] = 'selectall';
        $table->header('总记录数： ' . $table->count());
        $barNode = $table->bar;
        $barNode['style'] = "display:none;";
        $barNode->parent()['style'] = "display:none";

        $spanNode = $barNode->append("div", ['class' => 'selectcount']);
        $spanNode->append('font', ['当前选中']);
        $spanNode->append('font', [0, 'class' => 'count']);
        $spanNode->append('font', ['项']);

        $barNode->append('button', ['批量删除', 'class' => 'tbbtn', 'id' => 'deleteAll', 'data-action' => '?admin/task-delete,action:' . $action]);
        $formNode = $barNode->append('form', ['method' => 'post', 'id' => 'batchForm']);
        $formNode->append('input', ['type' => 'hidden', 'name' => 'ids', 'value' => '']);

        $table->paging($this->webapp->at(['page' => '']));


        $this->webapp->task->checkTaskDetail();
    }
    function get_task_fuck(string $hash = '')
    {
        $hash = trim($hash);
        $this->webapp->task->optimizeTaskExecuteTime($hash);
        $this->okay("?admin/task-detail,hash:{$hash}");
    }

    function get_task_paused(int $id, string $action = "like")
    {
        $this->webapp->mysql->table('task')('WHERE id=?i ', $id)->update(['status' => 'paused']);
        $this->okay("?admin/task,action:{$action}");
    }

    function get_task_start(int $id, string $action = "like", string $hash = '')
    {
        $this->webapp->mysql->table('task')('WHERE id=?i ', $id)->update(['status' => 'running']);
        $this->webapp->task->optimizeTaskExecuteTime($hash);
        $this->okay("?admin/task,action:{$action}");
    }

    function get_task_delete(int $id, string $action = "like")
    {
        $this->webapp->mysql->table('task')('WHERE id=?s ', $id)->update(['deleted_at' => date('Y-m-d H:i:s')]);
        $this->webapp->task->afterDelete($id);
        $this->okay("?admin/task,action:{$action}");
    }
    function post_task_delete(string $action)
    {
        $ids = trim($this->webapp->request_content()['ids'] ?? "", ',');
        if ($ids) {
            $this->webapp->mysql->table('task')('WHERE id IN ( ' . $ids . ')')->update(['deleted_at' => date('Y-m-d H:i:s')]);
            foreach (explode(",", $ids) as $id) {
                $this->webapp->task->afterDelete($id);
            }
        }
        $this->okay("?admin/task,action:{$action}");
    }


    function raddomLyrics()
    {
        $file = fopen(__DIR__ . '/models/jay_lyrics.txt', "r");
        $line = 0;
        $lines = [];
        while (!feof($file)) {
            $lines[] = fgets($file);
            $line++;
        }
        fclose($file);
        $rand = rand(0, $line - 1);
        return $lines[$rand];
    }
}





return new class extends webapp
{

    public $rds, $task;
    function __construct()
    {
        $config = require('local.config.php');
        parent::__construct($config['webapp']);
        $this->rds = RedisManager::getInstance($config['redis']);
        $this->task = new Task($this);
    }
    function get_home() {}
};
